package com.example.night.service.ApiService.yuantuitui;

import com.example.night.data.Good.Good;
import com.example.night.data.Good.GoodData;
import com.example.night.data.Good.GoodPackage;
import com.example.night.data.Good.GoodResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.scheduling.annotation.Async;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Slf4j
@Service
public class GoodService {

    private static final String BASE_URL = "https://b.yuantuitui.com/api/product/list?";
    private final LoginService loginservice;
    private static String token = "";
    private static final String UPDATE_URL = "https://b.yuantuitui.com/api/product/oneclicksync?IsIncrement=1";

    public GoodService(LoginService loginservice) {
        this.loginservice = loginservice;
    }

    public Map<String, Object> fetchGoods(int page, String search) throws JsonProcessingException, ExecutionException, InterruptedException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        token = loginservice.getToken();

        String AUTHORIZATION = "Bearer " + token;

        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(AUTHORIZATION.split(" ")[1]);

        Map<String, Object> requestBody = new HashMap<>();

        requestBody.put("status", 0);
        requestBody.put("product_id_or_title", search);
        requestBody.put("shop_name", "");
        requestBody.put("category", 0);
        requestBody.put("tag_ids", new ArrayList<>());
        requestBody.put("shop_ids", new ArrayList<>());
        requestBody.put("time", new HashMap<>());
        requestBody.put("promotion_end_time", new HashMap<>());
        requestBody.put("price", new HashMap<>());
        requestBody.put("cos_ratio", new HashMap<>());
        requestBody.put("refine_status", 0);
        requestBody.put("activity_type", -1);
        requestBody.put("deliver", -1);
        requestBody.put("is_free", -1);

        ObjectMapper objectMapper = new ObjectMapper();
        String requestBodyString = objectMapper.writeValueAsString(requestBody);
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBodyString, headers);
        List<GoodPackage> goodPackages = new ArrayList<>();
        try {
            String url = BASE_URL +
                    "sort=0&" +
                    "sort_field=add_time&" +
                    "limit=15&" +
                    "page=" + page;
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                String responseBody = responseEntity.getBody();
                GoodResponse goodResponse = objectMapper.readValue(responseBody, GoodResponse.class);
                if (goodResponse.getCode() == 200 && goodResponse.getData().isSuccess()) {
                    log.info("成功获取商品列表，总数：{}", goodResponse.getData().getResult().getItems().size());
                    List<Good> goods = goodResponse.getData().getResult().getItems();
                    for (Good good : goods) {
                        GoodPackage goodPackage = new GoodPackage();
                        goodPackage.setRelateProductImg(good.getCover());
                        goodPackage.setRelateProductName(good.getTitle());
                        goodPackage.setRelateProductId(good.getProductId());
                        goodPackage.setLinkUrl(good.getActivityUrl());
                        goodPackage.setLinkStartTime(convertTimestampToString(good.getPromotionStartTime(), "yyyy-MM-dd HH:mm:ss"));
                        goodPackage.setLinkEndTime(convertTimestampToString(good.getPromotionEndTime(), "yyyy-MM-dd HH:mm:ss"));
                        goodPackage.setPartnerShopId(good.getShop().getShopId());
                        goodPackage.setPartnerShopName(good.getShop().getName());
                        goodPackage.setCommissionMargin(good.getCosRatio());
                        goodPackage.setActivityCommissionMargin(good.getKolCosRatio());
                        goodPackage.setRelateSpecLivePrice(good.getPrice() / 100);
                        goodPackage.setServiceMargin(good.getServiceRatio() / 100);
                        goodPackage.setRelateGoodsStock(good.getStockNum());
                        goodPackage.setOriginInstitutionName(good.getOriginInstitutionName());
                        goodPackages.add(goodPackage);
                    }
                    int totalGoods = goodResponse.getData().getResult().getPagination().getTotalCount();
                    int totalPages = (totalGoods + 14) / 15;
                    return Map.of(
                            "total_goods", totalGoods,
                            "total_pages", totalPages,
                            "goods", goodPackages,
                            "success", true
                    );
                } else {
                    log.error("获取商品列表失败：{}", goodResponse.getMessage());
                }
            } else {
                log.warn("请求失败，状态码：{}", responseEntity.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("请求异常: {}", e.getMessage(), e);
//            login();
        }
        return Map.of("success", false);
    }

    public static String convertTimestampToString(long timestamp, String pattern) {
        if (String.valueOf(timestamp).length() == 10) {
            timestamp *= 1000;
        }
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public GoodPackage findGoodById(String id) throws JsonProcessingException, ExecutionException, InterruptedException {
        List<GoodPackage> goodPackages = (List<GoodPackage>) fetchGoods(1, id).get("goods");
        if (goodPackages.isEmpty()) {
            updateProduct();
        }
        goodPackages = (List<GoodPackage>) fetchGoods(1, id).get("goods");
        if (goodPackages != null && !goodPackages.isEmpty()) {
            return goodPackages.get(0);
        }
        return null;
    }

    @Scheduled(cron = "0 1 0 * * ?")
    public void updateProduct() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        String AUTHORIZATION = "Bearer " + token;
        token = loginservice.getToken();

        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(AUTHORIZATION.split(" ")[1]);

        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>("", headers);
        ResponseEntity<String> response = restTemplate.exchange(UPDATE_URL, HttpMethod.POST, requestEntity, String.class);
        log.info("商品更新结果：{}", response.getBody());
    }

    @PostConstruct
    public void init() throws JsonProcessingException, ExecutionException, InterruptedException {
        log.info("初始化商品服务");

//        login();

        if (token != "") {
            fetchGoods(1, "");  // 执行 fetchGoods 操作
        }
    }
    @Async
    public void login() throws ExecutionException, InterruptedException {
        loginservice.sendCodeAndLogin();
        token = loginservice.getToken();
    }
}
